﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;

namespace XamlFoundation.IoC
{
    public class DependencyContainer
    {
        #region Private Members

        private readonly Dictionary<Type, object> _instances = new Dictionary<Type, object>();
        private readonly Dictionary<Type, Type> _mappings = new Dictionary<Type, Type>();

        #endregion

        /// <summary>
        /// Initializes a new instance of the <see cref="DependencyContainer" /> class.
        /// </summary>
        public DependencyContainer()
        {
            _instances.Add(typeof(DependencyContainer), this);
        }

        /// <summary>
        /// Registers an instance
        /// </summary>
        /// <param name="instance">The instance.</param>
        public void RegisterInstance(object instance)
        {
            var type = instance.GetType();
            _instances.Add(type, instance);
        }

        /// <summary>
        /// Registers an instance
        /// </summary>
        /// <param name="instance">The instance.</param>
        public void RegisterInstance<T>(object instance)
        {
            _instances.Add(typeof(T), instance);
        }

        /// <summary>
        /// Registers the specified type for the specified interface
        /// </summary>
        public void RegisterType<TInterface, TImpl>()
        {
            _mappings.Add(typeof(TInterface), typeof(TImpl));
        }

        /// <summary>
        /// Gets all instances of a specified type of interface
        /// </summary>
        public IEnumerable<T> GetAll<T>()
        {
            return _instances.Values.OfType<T>();
        }

        public T Resolve<T>()
        {
            return (T)Resolve(typeof(T));
        }

        public T ResolveNew<T>()
        {
            _instances.Remove(typeof(T));
            return (T)Resolve(typeof(T));
        }

        public object Resolve(Type type)
        {

            // Instance already created
            if (_instances.ContainsKey(type))
            {
                return _instances[type];
            }

            // create from interface
            if (type.IsInterface)
            {
                if (_mappings.ContainsKey(type))
                {
                    return ResolveComplex(type);
                }

                throw new ArgumentException("No typemapping for interface " + type);
            }

            // Create from class
            var obj = ResolveComplex(type);
            return obj;
        }

        private object ResolveComplex(Type type)
        {
            Type implType = type;

            if (type.IsInterface)
            {
                implType = _mappings[type];
            }

            try
            {
                var constructor = implType.GetConstructors().First(c => (c.Attributes & MethodAttributes.Static) == 0);
                var parameters = constructor.GetParameters();
                var impl = Activator.CreateInstance(implType, parameters.Select(parameter => Resolve(parameter.ParameterType)).ToArray());
                _instances.Add(type, impl);
                return impl;
            }
            catch (Exception ex)
            {
                if (ex.InnerException != null)
                {
                    ex = ex.InnerException;
                }
                throw ex;
            }
        }
    }

}
